package com.zhou.config;

import brave.Tracer;
import brave.propagation.TraceContext;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

/**
 * StaticAttributeSetFilter
 *
 * @author zhouxianfeng
 * @date 2021-5-17
 */
/*@WebFilter(filterName = "StaticAttributeSetFilter", urlPatterns = "/*")
@Order(1) //测试好像这个参数不生效，实际生效的是Filter扫描到的顺序（所以起名很重要）*/
public class StaticAttributeSetFilter implements Filter {

    @Autowired
    private Tracer tracer;

    private static final String key = "traceId";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        Locale locale = request.getLocale();
        //validator中的locale
        if (tracer.currentSpan() != null) {
            TraceContext context = tracer.currentSpan().context();
            if (response instanceof HttpServletResponse) {
                HttpServletResponse resp = (HttpServletResponse) response;
                resp.addHeader("traceId", context.traceIdString());
            }
        }
        chain.doFilter(request, response);
    }
}